package problem1219;

//1219.黄金矿工
//https://leetcode.cn/problems/path-with-maximum-gold/

class Solution {
    int[] xx = {1,-1,0,0};
    int[] yy = {0,0,1,-1};
    boolean[][] st;
    int n, m, ret;
    public int getMaximumGold(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        st = new boolean[n][m];
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                if(grid[i][j] != 0) {
                    st[i][j] = true;
                    dfs(grid, i, j, grid[i][j]);
                    st[i][j] = false;
                }
            }
        }
        return ret;
    }
    public void dfs(int[][] grid, int x, int y, int sum) {
        ret = Math.max(ret, sum);

        for(int i = 0; i<4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && !st[dx][dy] && grid[dx][dy] != 0) {
                st[dx][dy] = true;
                dfs(grid, dx, dy, sum + grid[dx][dy]);
                st[dx][dy] = false;
            }
        }
    }
}